package cn.swpu.blog.service.impl;

import cn.swpu.blog.dao.TagMapper;
import cn.swpu.blog.entity.Tag;
import cn.swpu.blog.exception.TagNotFoundException;
import cn.swpu.blog.service.ITagService;
import cn.swpu.blog.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.StringHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 冰翔
 * @Date Created in 4:24 下午 2020/12/11
 */
@Slf4j
@Service
public class TagServiceImpl implements ITagService {

    @Autowired
    private TagMapper tagMapper;

    @Override
    public ResponseVo<Map<String, String>> queryTag(Integer tagId) {
        Tag tag = tagMapper.selectByPrimaryKey(tagId);

        //统一异常处理
        if (tag == null) {
            throw new TagNotFoundException("标签Id="+tagId);
        }

        Map<String, String> map = new HashMap<>(1);
        map.put("tag", tag.getTag());

        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo<List<Tag>> queryTagByList(List<Integer> tagIdList) {
        //一次查出所有tag
        List<Tag> tags = tagMapper.selectAll();

        //将list转化未Map（tagId, Tag）
        Map<Integer, Tag> tagMap = tags.stream().collect(Collectors.toMap(Tag::getTagId, tag -> tag));

        //根据list中的值查标签
        List<Tag> tagList = new ArrayList<>();
        for (Integer tagId : tagIdList) {
            Tag tag = tagMap.get(tagId);

            //统一异常处理
            if (tag == null) {
                throw new TagNotFoundException("标签Id="+tagId);
            }

            tagList.add(tag);
        }

        return ResponseVo.success(tagList);
    }

    @Override
    public ResponseVo<List<Tag>> queryAll() {
        List<Tag> tagList = tagMapper.selectAll();
        return ResponseVo.success(tagList);
    }

    @Override
    public ResponseVo<Map<String, Integer>> createTag(String tag) {
        Tag record = new Tag();
        record.setTag(tag);
        tagMapper.insertTagByString(record);

        Map<String, Integer> map = new HashMap<>(1);
        map.put("tagId", record.getTagId());

        return ResponseVo.success(map);
    }

    @Override
    public ResponseVo<Tag> deleteTag(Integer tagId) {

        Tag tag = tagMapper.selectByPrimaryKey(tagId);

        if (tag == null) {
            throw new TagNotFoundException("删除标签失败");
        }

        tagMapper.deleteByPrimaryKey(tagId);
        return ResponseVo.success(tag);
    }

    @Override
    public ResponseVo<Tag> updateTag(Tag tag) {
        int result = tagMapper.updateByPrimaryKey(tag);

        //因为tagId为基本类型，不涉及自动装箱拆箱，所以可以采用'=='比较
        if (result != 1) {
            throw new TagNotFoundException("更新标签失败");
        }
        Tag tagUpdated = tagMapper.selectByPrimaryKey(tag.getTagId());

        return ResponseVo.success(tagUpdated);
    }
}
